package com.aster.service.manage.controller;

import com.aster.common.annotation.Log;
import com.aster.common.base.BaseController;
import com.aster.common.base.BaseDomain;
import com.aster.common.dto.UserToken;
import com.aster.common.exception.ServiceException;
import com.aster.common.utils.PageUtils;
import com.aster.common.utils.Query;
import com.aster.common.utils.R;
import com.aster.service.manage.dao.EscortEnterpriseInfoDao;
import com.aster.service.manage.domain.TbEnterpriseProfitRatioInfo;
import com.aster.service.manage.domain.TbEscortEnterpriseInfo;
import com.aster.service.manage.dto.DtoEscortEnterpriseInfo;
import com.aster.service.manage.dto.do2dto.EscortEnterpriseInfoConvert;
import com.aster.service.manage.service.EnterpriseProfitRatioInfoService;
import com.aster.service.manage.service.EscortEnterpriseInfoService;
import com.aster.service.manage.service.criteria.EscortEnterpriseInfoCriteria;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * <br>
 * <b>功能：</b>TbEscortEnterpriseInfoController<br>
 *   <br>
 */
@RestController
@RequestMapping("/enterprise")
public class EscortEnterpriseInfoController extends BaseController {
	
	private final static Logger log= Logger.getLogger(EscortEnterpriseInfoController.class);
	@Autowired(required=false) 
	private EscortEnterpriseInfoService tbEscortEnterpriseInfoService;
	@Autowired(required=false)
	private EnterpriseProfitRatioInfoService enterpriseProfitRatioInfoService;
	@Autowired
	private EscortEnterpriseInfoDao escortEnterpriseInfoDao;

	@Log("陪护企业列表")
	@GetMapping
	public R listByPage(@RequestParam Map<String, Object> params){
		Query query = new Query(params);
		EscortEnterpriseInfoCriteria criteria = new EscortEnterpriseInfoCriteria();
		criteria.setPageSize(query.getLimit());
		criteria.setCurrentPage(query.getPage());
		Map<String,Object> likeMap = new HashMap<>();
		likeMap.put("name",query.get("name"));
		criteria.setConditionLike(likeMap);
		Map<String,Object> map = new HashMap<>();
		map.put("deleted",1);
		criteria.setCondition(map);
		criteria.setOrderByClause("id");
		PageUtils pageUtils = tbEscortEnterpriseInfoService.getEscortEnterpriseInfoForPage(criteria);
		return R.ok().put("page",pageUtils);
	}

	@Log("获取全部企业信息")
	@GetMapping("/getList")
	public R getList(){
		try{
			EscortEnterpriseInfoCriteria criteria = new EscortEnterpriseInfoCriteria();
			Map<String,Object> map = new HashMap<>();
			map.put("deleted",1);
			map.put("state",1);
			criteria.setCondition(map);
			criteria.setOrderByClause("id");
			criteria.setCurrentPage(1);
			Integer totalCount = tbEscortEnterpriseInfoService.queryByCount(criteria);
			criteria.setPageSize(totalCount);
			List<TbEscortEnterpriseInfo> list = tbEscortEnterpriseInfoService.queryByList(criteria);
			List<DtoEscortEnterpriseInfo> dtoList = EscortEnterpriseInfoConvert.MAPPER.dos2dtos(list);
			return R.ok().put("info",dtoList);
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}catch (NumberFormatException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("根据id获取用户信息")
	@RequestMapping("/getById")
	public R getById(@RequestParam Map<String, Object> params){
		try{
			String idStr = (String) params.get("id");
			int id = Integer.parseInt(idStr);
			TbEscortEnterpriseInfo info = tbEscortEnterpriseInfoService.queryById(id);
			DtoEscortEnterpriseInfo dtoEscortEnterpriseInfo = EscortEnterpriseInfoConvert.MAPPER.do2dto(info);
			// 根据ID获取分润,还有数据状态
			TbEnterpriseProfitRatioInfo enterpriseProfitRatioInfo = new TbEnterpriseProfitRatioInfo();
			enterpriseProfitRatioInfo.setState(0);
			enterpriseProfitRatioInfo.setEnterpriseId(id);
			enterpriseProfitRatioInfo = enterpriseProfitRatioInfoService.queryByEnterpriseIdAndState(enterpriseProfitRatioInfo);
			if (enterpriseProfitRatioInfo != null){
				dtoEscortEnterpriseInfo.setProfitRetio(enterpriseProfitRatioInfo.getProfitRetio());
			}
			return R.ok().put("info",dtoEscortEnterpriseInfo);
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}catch (NumberFormatException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("添加企业信息")
	@PostMapping("/add")
	public R add(@RequestBody DtoEscortEnterpriseInfo dtoEscortEnterpriseInfo, HttpServletRequest headers){
		try {
			UserToken userToken = getUserToken(headers);
			if(userToken == null){
				return R.error401();
			}
			TbEscortEnterpriseInfo tbEscortEnterpriseInfo = EscortEnterpriseInfoConvert.MAPPER.addData(dtoEscortEnterpriseInfo);
			tbEscortEnterpriseInfoService.addEscortEnterpriseInfo(tbEscortEnterpriseInfo,userToken);

			Integer profit_retio = dtoEscortEnterpriseInfo.getProfitRetio();
			//取出所存储企业的id
			TbEscortEnterpriseInfo enterpriseInfo =escortEnterpriseInfoDao.selectByOne(tbEscortEnterpriseInfo);
			if (profit_retio != null){
				// 存储分润
				TbEnterpriseProfitRatioInfo tbEnterpriseProfitRatioInfo = new TbEnterpriseProfitRatioInfo();
				tbEnterpriseProfitRatioInfo.setEnterpriseId(enterpriseInfo.getId());
				tbEnterpriseProfitRatioInfo.setProfitRetio(profit_retio);
				enterpriseProfitRatioInfoService.addEnterpriseProfitRatioInfo(tbEnterpriseProfitRatioInfo,userToken);
			}
			return R.ok();
		}
		catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("编辑企业信息")
	@PostMapping("/edit")
	public R editState(@RequestBody DtoEscortEnterpriseInfo dtoEscortEnterpriseInfo, HttpServletRequest headers){
		try {
			UserToken userToken = getUserToken(headers);
			TbEscortEnterpriseInfo tbEscortEnterpriseInfo = EscortEnterpriseInfoConvert.MAPPER.dto2do(dtoEscortEnterpriseInfo);
			tbEscortEnterpriseInfoService.editEscortEnterpriseInfo(tbEscortEnterpriseInfo,userToken);

			// 获取出当前企业的分润
			TbEnterpriseProfitRatioInfo enterpriseProfitRatioInfo = new TbEnterpriseProfitRatioInfo();
			enterpriseProfitRatioInfo.setEnterpriseId(dtoEscortEnterpriseInfo.getId());
			enterpriseProfitRatioInfo.setState(0);
			enterpriseProfitRatioInfo = enterpriseProfitRatioInfoService.queryByEnterpriseIdAndState(enterpriseProfitRatioInfo);
			if (enterpriseProfitRatioInfo != null){
				// 如果编辑的分润值跟分润表最新的值不一致，则更新分润表
				if (enterpriseProfitRatioInfo.getProfitRetio() != dtoEscortEnterpriseInfo.getProfitRetio()){
					enterpriseProfitRatioInfo.setUpdateTime(new Date());
					enterpriseProfitRatioInfo.setUpdateUserId(Integer.parseInt(userToken.getUserId()));
					enterpriseProfitRatioInfo.setState(1);
					enterpriseProfitRatioInfoService.update(enterpriseProfitRatioInfo);
					// 新增一个分润拉链
					TbEnterpriseProfitRatioInfo lastInfo = new TbEnterpriseProfitRatioInfo();
					lastInfo.setEnterpriseId(dtoEscortEnterpriseInfo.getId());
					lastInfo.setProfitRetio(dtoEscortEnterpriseInfo.getProfitRetio());
					enterpriseProfitRatioInfoService.addEnterpriseProfitRatioInfo(lastInfo,userToken);
				}
			}else {
				//如果没有过分润值，则 新增一个分润拉链
				TbEnterpriseProfitRatioInfo lastInfo = new TbEnterpriseProfitRatioInfo();
				lastInfo.setEnterpriseId(dtoEscortEnterpriseInfo.getId());
				lastInfo.setProfitRetio(dtoEscortEnterpriseInfo.getProfitRetio());
				enterpriseProfitRatioInfoService.addEnterpriseProfitRatioInfo(lastInfo,userToken);
			}
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("删除企业信息")
	@PostMapping("/delete")
	public R delete(@RequestBody DtoEscortEnterpriseInfo dtoEscortEnterpriseInfo,HttpServletRequest headers){
		try{
			if(dtoEscortEnterpriseInfo == null){
				return R.error(10001,"传入参数为空");
			}
			if(dtoEscortEnterpriseInfo.getId() == 0){
				return R.error(10001,"传入参数为空");
			}
			UserToken userToken = getUserToken(headers);
			if(userToken == null){
				return R.error401();
			}
			dtoEscortEnterpriseInfo.setDeleted(BaseDomain.DELETED.NO.key);
			TbEscortEnterpriseInfo tbEscortEnterpriseInfo = EscortEnterpriseInfoConvert.MAPPER.updateDeleted(dtoEscortEnterpriseInfo);
			tbEscortEnterpriseInfoService.editEscortEnterpriseInfo(tbEscortEnterpriseInfo,userToken);
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}

	@Log("修改企业数据状态")
	@PostMapping("/changeState")
	public R changeState(@RequestBody DtoEscortEnterpriseInfo dtoEscortEnterpriseInfo,HttpServletRequest headers){
		try {
			if(dtoEscortEnterpriseInfo == null){
				return R.error(10001,"传入参数为空");
			}
			if(dtoEscortEnterpriseInfo.getId() == 0){
				return R.error(10001,"传入参数为空");
			}
			UserToken userToken = getUserToken(headers);
			if(userToken == null){
				return R.error401();
			}
			TbEscortEnterpriseInfo tbEscortEnterpriseInfo = EscortEnterpriseInfoConvert.MAPPER.updateState(dtoEscortEnterpriseInfo);
			tbEscortEnterpriseInfoService.editEscortEnterpriseInfo(tbEscortEnterpriseInfo,userToken);
			return R.ok();
		}catch (ServiceException ex){
			return R.error(ex.getMessage());
		}
		catch (Exception ex){
			return R.error(ex.getMessage());
		}
	}
}
